package com.briup.day19;

import java.util.Set;
import java.util.TreeSet;

/**
 * @author ThinkBook
 */
public class Test02_TreeSet {
    public static void main(String[] args) {
        // TreeSet添加自定义Person对象
        Person p1 = new Person("tom",19);
        Person p2 = new Person("tom",19);
        Person p3 = new Person("jack",20);
        Person p4 = new Person("rose",18);
        Person p5 = new Person("lily",21);
        Set<Person> set = new TreeSet<>();
        set.add(p1);
        set.add(p2);
        set.add(p3);
        set.add(p4);
        set.add(p5);

        //遍历
        for(Person p : set) {
            System.out.println(p);
        }
    }
    public static void main02(String[] args) {
        Set<String> set = new TreeSet<>();
        set.add("hello");
        set.add("123");
        set.add("nihao");
        set.add("world");
        System.out.println(set);
    }
    //TreeSet存储多个Integer对象
    public static void main01(String[] args) {
        Set<Integer> set = new TreeSet<>();
        set.add(7);
        set.add(9);
        set.add(1);
        set.add(3);
        set.add(3);
        set.add(10);
        set.add(8);

        System.out.println(set);
    }
}
class Person implements Comparable{
    private String name;
    private int age;

    public Person() {}
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
    /*
       自然排序算法: this o
           由this比较o: 升序

        */
    @Override
    public int compareTo(Object o) {
        //name ,age两个比较值
        Person p = (Person)o;
        //按照年龄进行比较，升序，如果年龄相同则按照姓名排序（降序）
        int r = this.age - p.age;
        if (r ==0){
            //按name降序
            //r = p.name - this.name; ERROR
            r = p.name.compareTo(this.name);
        }

        //如果返回值为0：表示两个对象 相同
        return r;
    }
}
